package com.msx.user.producer;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.msx.pojo.Operator;
import com.msx.pojo.Sms;
import com.msx.user.service.OperatorServiceInterface;
import com.msx.user.service.impl.OperatorService;
import com.msx.user.service.impl.Smslmpl;
import com.msx.util.ResponseResult;
import com.msx.util.StatusCode;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * 运营商服务
 */
@Service(timeout = 6000,retries=0,version = "2.0.0")
@Log4j2
public class OperatorServicelimpl implements OperatorServiceInterface {

    @Autowired
    private Smslmpl smslmpl;

    @Autowired
    private OperatorService operatorService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送消息
     * @param sms
     * @return
     */
    @Override
    public ResponseResult OutSms(Sms sms) {

        String mess = (String) redisTemplate.opsForValue().get(sms.getMobile() + sms.getUserId());

        //如果mess为空
        if (StringUtils.isBlank(mess)){
            //发送信息
            String outSms = smslmpl.sms(sms);

            //查看发送内容
            JSONObject jsonObject = JSON.parseObject(outSms);
            String data = jsonObject.getString("data");
            log.info("验证码为:"+data);

            //存入redis  三分钟
            redisTemplate.opsForValue().set(sms.getMobile(),data,3, TimeUnit.MINUTES);
            String o = (String) redisTemplate.opsForValue().get(sms.getMobile());
            //短信信息添加数据库
            smslmpl.SmsAdd(sms);

            //解决防刷问题
            redisTemplate.opsForValue().set(sms.getMobile()+sms.getUserId(),"获取运营商信息",1,TimeUnit.MINUTES);

            return new ResponseResult(StatusCode.OK,"验证码发送成功",outSms);
        }
        return new ResponseResult(StatusCode.ERROR,"请稍后再试",null);
    }

    /**
     * 运营商认证
     * @param operator
     * @return
     */
    @Override
    public ResponseResult IdentityOperator(Operator operator) {
        String num = (String) redisTemplate.opsForValue().get(operator.getMobile());
        log.info("验证码为:"+num);
        if (operator.getCode().equals(num)){
            return operatorService.IdentityOperator(operator);
        }
        return new ResponseResult(StatusCode.LOGINERROR,"验证码已过期",null);
    }

    @Override
    public ResponseResult findOperatorByUserId(Integer userId) {
        return operatorService.findOperatorByUserId(userId);
    }
}
